<template>
  <div class="grade-view">
    <a-card title="成绩视图">
      <template #extra>
        <a-button @click="$router.back()">返回</a-button>
      </template>

      <!-- 搜索表单 -->
      <a-form layout="inline" class="search-form">
        <a-form-item label="学号">
          <a-input 
            v-model:value="searchForm.student_id" 
            placeholder="请输入学号" 
            style="width: 150px"
            @pressEnter="handleSearch"
          />
        </a-form-item>
        <a-form-item label="姓名">
          <a-input 
            v-model:value="searchForm.student_name" 
            placeholder="请输入姓名" 
            style="width: 120px"
            @pressEnter="handleSearch"
          />
        </a-form-item>
        <a-form-item label="专业">
          <a-input 
            v-model:value="searchForm.major" 
            placeholder="请输入专业" 
            style="width: 120px"
            @pressEnter="handleSearch"
          />
        </a-form-item>
        <a-form-item label="班级">
          <a-input 
            v-model:value="searchForm.class_name" 
            placeholder="请输入班级" 
            style="width: 120px"
            @pressEnter="handleSearch"
          />
        </a-form-item>
        <a-form-item label="学年">
          <a-select 
            v-model:value="searchForm.time" 
            placeholder="请选择" 
            style="width: 100px" 
            allow-clear
          >
            <a-select-option :value="2025">2025</a-select-option>
            <a-select-option :value="2024">2024</a-select-option>
            <a-select-option :value="2023">2023</a-select-option>
            <a-select-option :value="2022">2022</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item>
          <a-space>
            <a-button type="primary" @click="handleSearch">查询</a-button>
            <a-button @click="handleReset">重置</a-button>
          </a-space>
        </a-form-item>
      </a-form>

      <!-- 学生成绩卡片列表 -->
      <a-spin :spinning="loading">
        <div v-if="studentGrades.length === 0" style="text-align: center; padding: 40px; color: #999;">
          暂无数据，请先搜索学生
        </div>
        <div v-else class="student-cards">
          <a-card 
            v-for="student in studentGrades" 
            :key="student.student_id"
            class="student-card"
            :title="`${student.student_name}（${student.student_id}）`"
          >
            <template #extra>
              <a-space>
                <a-tag color="blue">{{ student.major }}</a-tag>
                <a-tag color="green">{{ student.class_name }}</a-tag>
                <a-tag color="purple">{{ student.time }}学年</a-tag>
              </a-space>
            </template>

            <div class="grade-summary">
              <a-statistic 
                title="课程总数" 
                :value="student.total_courses" 
                suffix="门"
                style="margin-right: 30px"
              />
              <a-statistic 
                title="平均分" 
                :value="student.avg_grade" 
                :precision="2"
                style="margin-right: 30px"
              />
              <a-statistic 
                title="及格率" 
                :value="student.pass_rate" 
                suffix="%"
                :precision="1"
                :value-style="{ color: student.pass_rate >= 80 ? '#3f8600' : '#cf1322' }"
              />
            </div>

            <a-divider />

            <!-- 课程成绩列表 -->
            <a-table 
              :columns="gradeColumns" 
              :data-source="student.grades" 
              :pagination="false"
              size="small"
              bordered
            >
              <template #bodyCell="{ column, record }">
                <template v-if="column.key === 'grade'">
                  <a-tag :color="Number(record.grade) >= 60 ? 'green' : 'red'">
                    {{ record.grade }}
                  </a-tag>
                </template>
                <template v-if="column.key === 'status'">
                  <span v-if="Number(record.grade) >= 90" style="color: #52c41a;">优秀</span>
                  <span v-else-if="Number(record.grade) >= 80" style="color: #1890ff;">良好</span>
                  <span v-else-if="Number(record.grade) >= 70" style="color: #faad14;">中等</span>
                  <span v-else-if="Number(record.grade) >= 60" style="color: #fa8c16;">及格</span>
                  <span v-else style="color: #f5222d;">不及格</span>
                </template>
              </template>
            </a-table>
          </a-card>
        </div>
      </a-spin>

      <!-- 分页 -->
      <div v-if="studentGrades.length > 0" style="margin-top: 20px; text-align: center;">
        <a-pagination
          v-model:current="pagination.current"
          v-model:page-size="pagination.pageSize"
          :total="pagination.total"
          :show-total="(total: number) => `共 ${total} 个学生`"
          @change="handlePageChange"
        />
      </div>
    </a-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { message } from 'ant-design-vue'
import { gradeAPI } from '@/api/grade'
import type { GradeDetail } from '@/api/grade'

const loading = ref(false)

interface StudentGrade {
  student_id: string
  student_name: string
  major: string
  class_name: string
  time: number
  total_courses: number
  avg_grade: number
  pass_rate: number
  grades: GradeDetail[]
}

const studentGrades = ref<StudentGrade[]>([])

const searchForm = reactive({
  student_id: '',
  student_name: '',
  major: '',
  class_name: '',
  time: undefined as number | undefined
})

const pagination = ref({
  current: 1,
  pageSize: 5,
  total: 0
})

const gradeColumns = [
  { title: '课程名称', dataIndex: 'course_name', key: 'course_name' },
  { title: '成绩', dataIndex: 'grade', key: 'grade', width: 80, align: 'center' },
  { title: '等级', key: 'status', width: 80, align: 'center' }
]

// 加载数据
const loadData = async () => {
  if (!searchForm.student_id && !searchForm.student_name && !searchForm.major && !searchForm.class_name) {
    message.warning('请至少输入一个搜索条件')
    return
  }

  loading.value = true
  try {
    // 调用专门的成绩视图接口
    const res = await gradeAPI.getStudentView({
      student_id: searchForm.student_id || undefined,
      student_name: searchForm.student_name || undefined,
      major: searchForm.major || undefined,
      class_name: searchForm.class_name || undefined,
      time: searchForm.time,
      page: pagination.value.current,
      page_size: pagination.value.pageSize
    })

    if (res.data.code === 200) {
      studentGrades.value = res.data.data.results
      pagination.value.total = res.data.data.count
    } else {
      message.error(res.data.message || '加载失败')
    }
  } catch (error: any) {
    message.error('加载数据失败: ' + (error.response?.data?.message || error.message))
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pagination.value.current = 1
  loadData()
}

// 重置
const handleReset = () => {
  searchForm.student_id = ''
  searchForm.student_name = ''
  searchForm.major = ''
  searchForm.class_name = ''
  searchForm.time = undefined
  studentGrades.value = []
  pagination.value.current = 1
}

// 分页变化
const handlePageChange = () => {
  loadData()
}
</script>

<style scoped>
.search-form {
  margin-bottom: 20px;
}

.student-cards {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.student-card {
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.grade-summary {
  display: flex;
  margin-bottom: 20px;
}
</style>
